package com.young.common.client.log.core;

import com.young.common.util.StringUtils;
import com.young.interfaces.log.model.LogDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedList;

/**
 * Log上下文持有者
 * @author wangjiyu@imdada.cn
 * @create 2019/3/6
 */
public class LogContextHolder {
    private static final Logger logger = LoggerFactory.getLogger(LogContextHolder.class);
    //一个调用链会执行N个方法,对应着N个LogDTO
    private static final ThreadLocal<LinkedList<LogDTO>> logDTOContext = new ThreadLocal<LinkedList<LogDTO>>();

    /**
     * 设置当前方法上下文的logDTO
     * @param logDTO
     */
    static void setLogDTO(LogDTO logDTO) {
        LinkedList<LogDTO> linkedList = logDTOContext.get();
        if (linkedList == null) {
            linkedList = new LinkedList<LogDTO>();
            logDTOContext.set(linkedList);
        }
        linkedList.add(logDTO);
    }

    /**
     * 获取当前方法上下文的logDTO
     * @return
     */
    public static LogDTO getLogDTO() {
        LinkedList<LogDTO> linkedList = logDTOContext.get();
        if (linkedList == null) {
            return null;
        }
        return linkedList.getLast();
    }

    /**
     * 移除当前上下文的logDTO
     * @param logDTO 有值时用来验证删除的和预想的是否一致,根据uuid
     */
    static void removeLogDTO(LogDTO logDTO) {
        LinkedList<LogDTO> linkedList = logDTOContext.get();
        if (linkedList != null) {
            //删除最后一个
            LogDTO removeLog = linkedList.removeLast();
            if (removeLog != null && logDTO != null && !StringUtils.equals(removeLog.getUuid(), logDTO.getUuid())) {
                logger.error("[接口监控日志上下文-LogContextHolder.removeLogDTO] 接口监控日志上下文移除移除:移除项与验证项不一致,移除项UUID={},预期UUID={}", removeLog.getUuid(), logDTO.getUuid());
                throw new RuntimeException("接口监控日志上下文移除移除:移除项与验证项不一致");
            }
        }
    }
}
